from pickle import TRUE
from sanic.response import json,html
from sanic import Blueprint
from playhouse.shortcuts import model_to_dict,dict_to_model
from model.model import TCate,TPost

import time,uuid


rt = Blueprint("cate",url_prefix="cate")


# list
@rt.get("/")
def indexHandle(req):
    from mainapp import env
    tm = env.get_template("cate/index.html")
    rows = TCate.select()
    res = []
    for m in rows:
        res.append(model_to_dict(m))
    # return json({
    #         "msg":"DD"+str(uuid.uuid4()),
    #         "code":0,
    #         "data":res
    # })
    

    content = tm.render(data=res)
    return html(content)

# add
@rt.post("/")
def indexHandle(req):
    msg=""
    try:
        m = dict_to_model(TCate,req.json)
        m.cid=uuid.uuid1()
        m.createat=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        m.updateat=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        m.save(force_insert=TRUE)
        msg="ok"
    except Exception as e:
        msg = e
    return json({
            "msg":msg,
            "code":0,
            "data":{}
    })

# detail
@rt.get("/<id>")
def indexHandle(req,id):
    m = TCate.get_or_none(TCate.cid==id)
    res = m if (m is None) else model_to_dict(m)
    list = TPost.select().where(TPost.cid==id)
    from mainapp import env
    tm = env.get_template("cate/list.html")
    s = tm.render(data=res,list=list)

    return html(s)

# update
@rt.post("/<id>")
def indexHandle(req,id):
    m = TCate.get_or_none(TCate.cid==id)
    res = m if (m is None) else model_to_dict(m)
    return json({
            "msg":"this is book",
            "code":0,
            "data":res
    })



